package cn.etynit.service.impl;

import cn.etynit.domain.Product;
import cn.etynit.domain.PurchaseApply;
import cn.etynit.domain.StocWarningLog;
import cn.etynit.domain.Stock;
import cn.etynit.dto.StockDto;
import cn.etynit.exception.GlobalException;
import cn.etynit.exception.GlobalExceptionCodeEnum;
import cn.etynit.feign.ProductService;
import cn.etynit.feign.PurchaseService;
import cn.etynit.mapper.StockMapper;
import cn.etynit.properties.StockThresholdProperties;
import cn.etynit.result.JsonResult;
import cn.etynit.service.IStocWarningLogService;
import cn.etynit.service.IStockService;
import cn.etynit.util.AssertUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.xml.crypto.Data;
import java.util.Date;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author etyn
 * @since 2022-11-20
 */
@Service
public class StockServiceImpl extends ServiceImpl<StockMapper, Stock> implements IStockService {

    @Autowired
    private ProductService productService;

    @Autowired
    private StockThresholdProperties stockThresholdProperties;

    @Autowired
    private PurchaseService purchaseService;

    @Autowired
    private IStocWarningLogService stocWarningLogService;


    /**
     * 出入库
     */
    @Override
    public void iao(StockDto stockDto) {
        Stock stock = selectStock(stockDto.getProductId());
        if (stockDto.getStatus() == 0){ // 入库
            if (stock == null){
                stock = new Stock();
                stock.setCount(stockDto.getCount());
                stock.setProductId(stockDto.getProductId());
                JsonResult jsonResult = productService.get(stockDto.getProductId());
                AssertUtil.isTrue(jsonResult.isSuccess(), GlobalExceptionCodeEnum.ERROR);
                Object data = jsonResult.getData();
                AssertUtil.isNotNull(data, GlobalExceptionCodeEnum.ERROR);
                String jsonStr = JSONObject.toJSONString(data);
                Product product = JSON.parseObject(jsonStr, Product.class);
                stock.setProductName(product.getProductName());
                stock.setCreateTime(new Date());
                insert(stock);
            } else {
                stock.setCount(stock.getCount() + stockDto.getCount());
                updateById(stock);
            }
        } else { // 出库
            Integer count = stock.getCount();
            if (stock.getCount() < stockDto.getCount()){ // 库存不足
                // 判断库存数量是否小于警告阈值，小于记录警告日志，并调用采购服务进行申请
                if (count < stockThresholdProperties.getThreshold()){
                    Date date = new Date();
                    StocWarningLog stocWarningLog = new StocWarningLog();
                    BeanUtils.copyProperties(stock,stocWarningLog);
//                    stocWarningLog.setCurrentCount(count);
//                    stocWarningLog.setProductId(stock.getProductId());
//                    stocWarningLog.setProductName(stock.getProductName());
                    stocWarningLog.setInfo(stock.getProductName() + "库存不足，请及时采购！");
                    stocWarningLog.setCreateTime(date);
                    stocWarningLogService.insert(stocWarningLog);
                    PurchaseApply purchaseApply = new PurchaseApply();
                    BeanUtils.copyProperties(stock,purchaseApply);
                    purchaseApply.setCreateTime(date);
                    purchaseApply.setCount(100);
                    purchaseApply.setStatus(0);
                    purchaseService.saveOrUpdate(purchaseApply);
                    throw new GlobalException("库存不足，出库失败！");
                }
            } else { // 库存充足
                stock.setCount(stock.getCount() - stockDto.getCount());
                updateById(stock);
                PurchaseApply purchaseApply = new PurchaseApply();
                BeanUtils.copyProperties(stock,purchaseApply);
                purchaseApply.setCreateTime(new Date());
                purchaseApply.setCount(100);
                purchaseApply.setStatus(0);
                purchaseService.saveOrUpdate(purchaseApply);
                throw new GlobalException("库存不足，出库失败！");
            }
        }
    }

    /**
     * 查询库存是否缺货
     * @return
     */
    @Override
    public List<Stock> lack() {
        // 获取库存阈值
        Integer threshold = stockThresholdProperties.getThreshold();
        Wrapper<Stock> wapper = new EntityWrapper<>();
        wapper.lt("count",threshold);
        List<Stock> stocks = selectList(wapper);
        return stocks;
    }

    /**
     * 根据商品id去产库存
     * @param productId
     * @return
     */
    private Stock selectStock(Long productId) {
        EntityWrapper<Stock> wrapper = new EntityWrapper<>();
        wrapper.eq("product_id",productId);
        return selectOne(wrapper);
    }
}
